/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-02 10:21:02
 * @LastEditTime: 2019-09-02 10:55:43
 * @LastEditors: Please set LastEditors
 */
/*
 * @lc app=leetcode.cn id=24 lang=javascript
 *
 * [24] 两两交换链表中的节点
 *
 * https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
 *
 * algorithms
 * Medium (61.76%)
 * Likes:    272
 * Dislikes: 0
 * Total Accepted:    37.3K
 * Total Submissions: 60.2K
 * Testcase Example:  '[1,2,3,4]'
 *
 * 给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。
 * 
 * 你不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。
 * 
 * 
 * 
 * 示例:
 * 
 * 给定 1->2->3->4, 你应该返回 2->1->4->3.
 * 
 * 
 */
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
    if(!head) return null
    const left = []
    const right = []
    let isLeft = true
    while(head){
        if(isLeft){
            left.push(head)
        }else{
            right.push(head)
        }
        head = head.next
        isLeft = !isLeft
    }
    let ans = new ListNode()
    let a = ans
    while(left.length>0 && right.length>0){
        a.next = right.shift()
        a = a.next
        a.next = left.shift()
        a = a.next
    }
    a.next = left.shift() || right.shift()
    return ans.next
};

